package com.it.schoolhomeos.security;

import com.it.schoolhomeos.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import java.io.IOException;

public class JwtAuthorizationFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthorizationFilter.class);
    private static final String AUTHORIZATION_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";
    
    private final JwtUtil jwtUtil;
    private final CustomUserDetailsService userDetailsService;

    public JwtAuthorizationFilter(JwtUtil jwtUtil, CustomUserDetailsService userDetailsService) {
        this.jwtUtil = jwtUtil;
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        String header = request.getHeader("Authorization");
        logger.debug("Authorization头: {}", header);
        
        // 如果没有Bearer前缀，但有token，自动添加Bearer前缀
        if (header != null && !header.startsWith("Bearer ") && !header.isEmpty()) {
            header = "Bearer " + header;
            logger.debug("自动添加Bearer前缀: {}", header);
        }
        
        if (header == null || !header.startsWith("Bearer ")) {
            logger.warn("无效的Authorization头格式");
        }
        
        logger.debug("处理请求 - URL: {}, Method: {}", request.getRequestURI(), request.getMethod());
        
        // 对于登录请求，直接放行
        if (request.getRequestURI().equals("/api/auth/login") && request.getMethod().equals("POST")) {
            logger.debug("登录请求，直接放行");
            chain.doFilter(request, response);
            return;
        }
        
        // 对于OPTIONS请求，直接放行
        if (request.getMethod().equals("OPTIONS")) {
            logger.debug("OPTIONS请求，直接放行");
            chain.doFilter(request, response);
            return;
        }
        
        // 对于Swagger文档请求，直接放行
        if (request.getRequestURI().startsWith("/swagger-ui") || request.getRequestURI().startsWith("/v3/api-docs")) {
            logger.debug("Swagger文档请求，直接放行");
            chain.doFilter(request, response);
            return;
        }
        
        // 如果没有token，继续过滤器链
        if (header == null || !header.startsWith("Bearer ")) {
            logger.debug("请求中没有token或格式不正确");
            chain.doFilter(request, response);
            return;
        }
        
        // 提取token
        String token = header.substring(7);
        logger.debug("发现token: {}", token.substring(0, Math.min(token.length(), 10)) + "...");
        
        try {
            // 验证token
            if (jwtUtil.isTokenValid(token)) {
                logger.debug("token有效 - 用户: {}", jwtUtil.getUsernameFromToken(token));
                
                // 获取用户信息
                String username = jwtUtil.getUsernameFromToken(token);
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                
                // 创建认证对象
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                
                // 设置认证详情
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                
                // 设置认证信息到SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authentication);
                
                logger.debug("认证成功 - 用户: {}, 角色: {}", username, userDetails.getAuthorities());
            } else {
                logger.warn("token无效");
                // 清除认证信息
                SecurityContextHolder.clearContext();
                
                // 返回401错误
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"status\":\"error\",\"message\":\"token无效或已过期\"}");
                return;
            }
        } catch (Exception e) {
            logger.error("token验证失败", e);
            // 清除认证信息
            SecurityContextHolder.clearContext();
            
            // 返回401错误
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"status\":\"error\",\"message\":\"token验证失败: " + e.getMessage() + "\"}");
            return;
        }
        
        // 继续过滤器链
        chain.doFilter(request, response);
    }
} 